import { useFetch, useRuntimeConfig } from 'nuxt/app';
import type { UseFetchOptions } from 'nuxt/app';
import { useUserStore } from '~/store/useUser';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

interface RequestOptions extends UseFetchOptions<any> {
    customBaseURL?: string;
}

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type HandleRequestOptions = { request: Request; options: RequestOptions };
type HandleResponseOptions = { response: any };

// 请求拦截器
function handleRequest({ options }: HandleRequestOptions) {
    // 在 SSR 环境下安全地获取 token
    const token = process.client ? localStorage.getItem('token') : null;
    options.headers = {
        'Content-Type': 'application/json',
        'clientid': 'e5cd7e4891bf95d1d19206ce24a7b32e',
        'connection': 'keep-alive',
        'istoken': 'true',
        ...(token && { 'Authorization': `Bearer ${token}` }),
        ...options.headers,
    };
}

// 响应拦截器
function handleResponse({ response }: HandleResponseOptions) {
    console.log('response_1', response)
    if (response._data.error) {
        throw new Error(response._data.error.message || '响应错误');
    }
    
    // 处理401状态码
    if (response._data.code === 401) {
        if (process.client) {
            const userStore = useUserStore();
            const router = useRouter();
            
            // 防止重复处理401
            if (userStore.isLoggingOut) {
                return response;
            }
            
            ElMessage.error(response._data.msg || '登录已过期，请重新登录！');
            
            // 直接清除本地存储，不调用logout API避免循环
            try {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                userStore.userInfo = {};
                userStore.token = '';
                router.push('/login');
            } catch (error) {
                console.error('清除登录信息失败:', error);
            }
        }
    }
    
    return response;
}

/**
 * 创建请求方法
 * @param method
 */
function createUseFetchRequest(method: HttpMethod) {
    return async function (
        url: string,
        data?: any,
        options: RequestOptions = {}
    ) {
        return useFetch(url, {
            ...options,
            method,
            body: data,
            onRequest: handleRequest,
            onResponse: handleResponse
        });
    };
}

// 提供 useFetch & HTTP 方法 - 统一管理请求 - 再到组件中使用
export const useFetchGet = createUseFetchRequest('GET');
export const useFetchPost = createUseFetchRequest('POST');
export const useFetchPut = createUseFetchRequest('PUT');
export const useFetchDelete = createUseFetchRequest('DELETE');